package com.ecommerce.user.service.impl;

import com.ecommerce.common.exception.BusinessException;
import com.ecommerce.common.util.JwtUtil;
import com.ecommerce.user.dto.UserLoginRequest;
import com.ecommerce.user.dto.UserLoginResponse;
import com.ecommerce.user.dto.UserMapper;
import com.ecommerce.user.dto.UserRegisterRequest;
import com.ecommerce.user.dto.UserResponse;
import com.ecommerce.user.entity.User;
import com.ecommerce.user.repository.UserRepository;
import com.ecommerce.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder;

    @Override
    @Transactional
    public UserResponse register(UserRegisterRequest registerRequest) {
        log.info("用户注册请求: {}", registerRequest.getUsername());

        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerRequest.getUsername())) {
            throw new BusinessException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (userRepository.existsByEmail(registerRequest.getEmail())) {
            throw new BusinessException("邮箱已被注册");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(registerRequest.getUsername());
        user.setPassword(passwordEncoder.encode(registerRequest.getPassword()));
        user.setEmail(registerRequest.getEmail());
        user.setRoles(Collections.singleton("USER"));

        // 保存用户
        user = userRepository.save(user);
        log.info("用户注册成功: {}", user.getUsername());

        return userMapper.entityToResponseDto(user);
    }

    @Override
    public UserLoginResponse login(UserLoginRequest loginRequest) {
        log.info("用户登录请求: {}", loginRequest.getUsername());

        // 查找用户
        User user = userRepository.findByUsername(loginRequest.getUsername())
                .orElseThrow(() -> new BusinessException("用户名或密码错误"));

        // 验证密码
        if (!passwordEncoder.matches(loginRequest.getPassword(), user.getPassword())) {
            throw new BusinessException("用户名或密码错误");
        }

        // 生成JWT令牌
        List<String> rolesList = user.getRoles().stream().collect(Collectors.toList());
        String token = JwtUtil.generateToken(user.getUsername(), rolesList);
        
        // 构建响应
        UserResponse userResponse = userMapper.entityToResponseDto(user);
        UserLoginResponse loginResponse = new UserLoginResponse(token, userResponse);
        
        log.info("用户登录成功: {}", user.getUsername());
        return loginResponse;
    }

    @Override
    public UserResponse getUserById(Long userId) {
        log.info("根据ID获取用户信息: {}", userId);

        User user = userRepository.findById(userId)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        return userMapper.entityToResponseDto(user);
    }

    @Override
    public UserResponse getUserByUsername(String username) {
        log.info("根据用户名获取用户信息: {}", username);

        User user = userRepository.findByUsername(username)
                .orElseThrow(() -> new BusinessException("用户不存在"));
        
        return userMapper.entityToResponseDto(user);
    }
}